use core::fmt;
use core::ptr::{self, NonNull};
use lazy_static::lazy_static;
use spin::Mutex;

// --- 内存池定义 ---
const POOL_SIZE: usize = 1024; // 内存池大小

struct MemoryPool {
    pool: [u8; POOL_SIZE],
    offset: usize,
}

impl MemoryPool {
    const fn new() -> Self {
        Self {
            pool: [0; POOL_SIZE],
            offset: 0,
        }
    }

    fn alloc(&mut self, size: usize) -> *mut u8 {
        if self.offset + size > POOL_SIZE {
            panic!("Memory pool exhausted!");
        }
        let ptr = unsafe { self.pool.as_mut_ptr().add(self.offset) };
        self.offset += size;
        ptr
    }
}

lazy_static! {
    static ref MEMORY_POOL: Mutex<MemoryPool> = Mutex::new(MemoryPool::new());
}

// --- 链表节点 ---
#[derive(Clone, Copy)]
struct Node {
    ascii_char: u8,
    next: Option<NonNull<Node>>, // 使用 NonNull 避免空指针
}

// --- 字符串结构 ---
pub struct String {
    len: usize,
    head: Option<NonNull<Node>>, // 头节点
    tail: Option<NonNull<Node>>, // 尾节点（加速追加操作）
}

impl String {
    /// 创建一个空字符串
    pub fn new() -> Self {
        Self {
            len: 0,
            head: None,
            tail: None,
        }
    }

    /// 从 &str 初始化（无动态分配）
    pub fn from(s: &str) -> Self {
        let mut result = Self::new();
        result.push_str(s);
        result
    }

    /// 追加字符串（核心方法）
    pub fn push_str(&mut self, s: &str) {
        for &byte in s.as_bytes() {
            self.push_byte(byte);
        }
    }

    /// 追加单个字节
    fn push_byte(&mut self, byte: u8) {
        let new_node = self.alloc_node(byte);
        
        if let Some(mut tail) = self.tail {
            unsafe { tail.as_mut().next = Some(new_node) };
        } else {
            self.head = Some(new_node); // 第一个节点
        }
        
        self.tail = Some(new_node);
        self.len += 1;
    }

    /// 从内存池分配节点
    fn alloc_node(&mut self, byte: u8) -> NonNull<Node> {
        let mut pool = MEMORY_POOL.lock();
        let ptr = pool.alloc(core::mem::size_of::<Node>()) as *mut Node;
        
        unsafe {
            ptr.write(Node {
                ascii_char: byte,
                next: None,
            });
            NonNull::new(ptr).unwrap()
        }
    }

    /// 转换为 &str（需要外部提供缓冲区）
    pub fn to_str<'a>(&self, buffer: &'a mut [u8]) -> &'a str {
        let mut i = 0;
        let mut current = self.head;

        while let Some(node) = current {
            unsafe {
                if i >= buffer.len() {
                    break;
                }
                buffer[i] = node.as_ref().ascii_char;
                i += 1;
                current = node.as_ref().next;
            }
        }

        core::str::from_utf8(&buffer[..i]).unwrap()
    }



    
}

// --- 实现 Display 支持打印 ---
impl fmt::Display for String {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        let mut buffer = [0u8; 128]; // 栈上的临时缓冲区
        write!(f, "{}", self.to_str(&mut buffer))
    }
}

